<?php
class CSV extends File{
	
	var $deliminater;
	var $csvValues=array();
	
	function __construct($file=null,$deliminater=",") {
		 parent::__construct($file);
		 if($this->isString($deliminater)&&strlen($deliminater))
			 $this->deliminater=$deliminater;
	}

	
	
	function parseCSV($fieldNames=false,$removeQuotes=true){
		$contents=$this->fileLineToArray($this->file);
		if(!count($contents)) return false;
		foreach($contents as $csvLine){
			$csvValues=$this->csvLineToArray($csvLine);
			if($removeQuotes)
		    	$csvValues=$this->removeQuotes($csvValues);
			
		    if($this->isArray($fieldName)){
				$combinedArray=$this->setColumnNames();
		    }

			if($combinedArray===false)
				return false;
			
			$this->csvValues[]=$combinedArray;
		}
		
	}
	
	private function setColumnNames(){
		if(count($fieldNames)!=count($subQuery))
				return false;
		return ($combinedArray=array_combine( $fieldNames,$subQuery));
	}
	
	private function removeQuotes($csvValues){
	 	foreach($csvValues as $key=>$value){
	    	$csvValues[$key]=trim($value);
	    	if(strripos($value,'"')==(strlen($value)-1)&&stripos($value,'"')==0&&stripos($value,'"')!==false)
	    		$csvValues[$key]=substr  ( $value  , 1 ,-1 );
	    }
	    return $csvValues;
	}
	
	function fileLineToArray($file){
		$value=ini_get('auto_detect_line_endings');
		ini_set('auto_detect_line_endings',true);
		$array=array();
		if($this->isFile($file)){	
			$handle = fopen($file, "r");
			$array=array();
			if ($handle) {
				while (($data = fgetcsv($handle, 1000, ",")) !== FALSE){
			        $array[]=$data;
			    }
			    fclose($handle);
			}
		}
		ini_set('auto_detect_line_endings',$value);
		return $array;
	}	
	
	private function csvLineToArray($csvLine){
		$csvValues=explode(self::$DELIMINATER,$value);
		return $csvValues;
	}
	
}
	

?>